package com.fudan.adse.controller;

import com.fudan.adse.api.CommonResult;
import com.fudan.adse.domain.cont.AuthConstant;
import com.fudan.adse.domain.dto.OAuth2TokenDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jerry Zhang
 * create: 2022-10-28 16:43
 */
@RestController
@RequestMapping("/oauth")
public class AuthController {
    @Autowired
    private TokenEndpoint tokenEndpoint;

    /**
     * 接口必须为 /oauth/token，覆盖 oauth2 提供的接口
     *
     * @param request
     * @param grant_type
     * @param client_id
     * @param client_secret
     * @param refresh_token
     * @param username
     * @param password
     * @return
     * @throws HttpRequestMethodNotSupportedException
     */
    @PostMapping(value = "/token")
    public CommonResult<OAuth2TokenDTO> postAccessToken(HttpServletRequest request,
                                                        @RequestParam String grant_type,
                                                        @RequestParam String client_id,
                                                        @RequestParam String client_secret,
                                                        @RequestParam(required = false) String refresh_token,
                                                        @RequestParam(required = false) String username,
                                                        @RequestParam(required = false) String password) throws HttpRequestMethodNotSupportedException {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("grant_type", grant_type);
        parameters.put("client_id", client_id);
        parameters.put("client_secret", client_secret);
        parameters.putIfAbsent("refresh_token", refresh_token);
        parameters.putIfAbsent("username", username);
        parameters.putIfAbsent("password", password);
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(request.getUserPrincipal(), parameters).getBody();
        OAuth2TokenDTO oauth2TokenDto = OAuth2TokenDTO.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead(AuthConstant.JWT_TOKEN_PREFIX).build();

        return CommonResult.success(oauth2TokenDto);
    }

}
